<?php

namespace app\admin\controller\finance;

use addons\shopro\model\UserWalletLog;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;


/**
 * 钱包日志汇总
 *
 * @icon fa fa-circle-o
 */
class Walletrpt extends Backend
{
    /**
     * Activity模型对象
     * @var \app\admin\model\shopro\activity\Retailorder
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();

            }
            $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
            $order = $this->request->get("order", "DESC");
            $offset = $this->request->get("offset", 0);
            $limit = $this->request->get("limit", 0);

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            //SELECT type,FROM_UNIXTIME(createtime,'%Y-%m-%d') as date,sum(wallet) as sum_wallet,count(1) as cnt from fa_shopro_user_wallet_log where wallet_type='money' GROUP BY type,date order by date desc;

            $list = db('shopro_user_wallet_log')
                ->fieldRaw("type,FROM_UNIXTIME(createtime,'%Y-%m-%d') as date,sum(wallet) as sum_wallet,count(1) as cnt")
                ->where(['wallet_type'=>'money'])
                ->where($where)
                ->group("type,FROM_UNIXTIME(createtime,'%Y-%m-%d')")
                ->order($sort." ".$order)
                ->paginate($limit);

            $retdata = $list->items();
            foreach ($retdata as &$item){
                $item['type'] = UserWalletLog::getTypeName($item['type']);
            }
            $result = array("total" => $list->total(), "rows" => $retdata);

            return json($result);
        }
        return $this->view->fetch();
    }

}
